﻿using EFCore.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SService;

namespace WMSWeb.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PositionManagementController : ControllerBase
    {
        private readonly WmssystemContext myDbContext;
        private readonly PositionManagementS PositionManagementS;

        public PositionManagementController(WmssystemContext myDbContext, PositionManagementS PositionManagementS)
        {
            this.myDbContext = myDbContext;
            this.PositionManagementS = PositionManagementS;
        }
        /// <summary>
        /// 岗位管理分页模糊查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("FenYe")]
        public async Task<List<Sys_PositionManagement>> FenYe(int pageSize, int currentPage, string Key = null, string Status = null)
        {
            return await PositionManagementS.FenYe(pageSize, currentPage, Key, Status);
        }
        /// <summary>
        /// 岗位管理添加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<int>> Add(Sys_PositionManagement posAdd)
        {
            posAdd.P_IsDelete = true;
            //return await PositionManagementS.Add(posAdd);
            posAdd.P_MPositionCode = GenerateUniquePositionCode();

            // 调用服务层的添加方法
            var result = await PositionManagementS.Add(posAdd);

            return result;
        }
        /// <summary>
        /// 岗位管理删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<int>> Del(int id)
        {
            return await PositionManagementS.Del(id);
        }
        /// <summary>   
        /// 岗位管理修改
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public async Task<ActionResult<int>> Update(Sys_PositionManagement posUpd)
        {
            return await PositionManagementS.Upd(posUpd);
        }
        /// <summary>
        /// 岗位管理逻辑删除
        /// </summary>
        /// <returns></returns>
        [HttpPut("UpdIsDelete")]
        public async Task<ActionResult<int>> UpdIsDelete(int id, bool isDeleted)
        {
            return await PositionManagementS.UpdIsDelete(id, isDeleted);
        }
        //自动生成编号
        private string GenerateUniquePositionCode()
        {
            string prefix = "GWBH"; // 前缀
            string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss"); // 时间戳
            string randomSuffix = GenerateRandomNumericSuffix(4); // 随机后缀

            return $"{prefix}{timestamp}{randomSuffix}";
        }
        private string GenerateRandomNumericSuffix(int length)
        {
            Random random = new Random();
            const string chars = "0123456789";
            return new string(Enumerable.Repeat(chars, length)
              .Select(s => s[random.Next(s.Length)]).ToArray());
        }
    }
}
